package com.mima.minaserver.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Date;

import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import com.mima.minaserver.repository.CameraRepository;
import com.mima.minaserver.service.IotServerMessage;
import com.mima.minaserver.service.MessageSender;
import com.mima.minaserver.service.RabbitMQListener;
import com.mima.minaserver.utils.ParameterUtils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

@Service
@Configuration
public class IOTServer {

	@Autowired
	private IOTServerHandler iotServerHandler;
	@Autowired
    CacheManager cacheManager;
	@Autowired
	private ParameterUtils parameterUtils;
	@Autowired
	private IotServerMessage iotServerMessage;
	@Autowired
	private CameraRepository cameraRepository;
	
	@Autowired 
	MessageSender messageSender;
	
	public IOTServer() {
	}
	
	public void startUDPServer() {
		try {			
			initEhCache();
			NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
			acceptor.getFilterChain().addLast("codec",  
	                    new ProtocolCodecFilter(new ByteArrayCodecFactory())); 
		        acceptor.setHandler(iotServerHandler);
		        acceptor.bind(new InetSocketAddress(parameterUtils.getMina_server_ip(),parameterUtils.getMina_server_port()));
		        startRabbitMQListener();   
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void initEhCache() { 
        
        Cache cache = cacheManager.getCache(parameterUtils.getSession_cache());
        if(cache == null) { 
            Cache memoryOnlyCache = new Cache(parameterUtils.getSession_cache(), 5000, false, false, 5, 2);   
            cacheManager.addCache(memoryOnlyCache);  
        }
	}
	public void startRabbitMQListener() {
		new Thread(new RabbitMQListener(iotServerMessage, cacheManager,cameraRepository, parameterUtils)).start();
	}
	@Bean
	public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean) {
		return new EhCacheCacheManager(bean.getObject());
	}
	
	@Bean
	public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
		EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
        cacheManagerFactoryBean.setConfigLocation (new ClassPathResource ("/ehcache.xml"));
        cacheManagerFactoryBean.setShared (true);
        return cacheManagerFactoryBean;
	}
}
